package com.atguigu.yygh.sms.controller;

import com.atguigu.yygh.result.Result;
import com.atguigu.yygh.sms.service.SmsService;
import com.atguigu.yygh.sms.util.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author zr
 * @date 2021/12/16 19:09
 */
@Api(tags = "短信管理")
@RestController
@RequestMapping("/api/sms")
public class SmsApiController {
    @Resource
    private SmsService smsService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @ApiOperation("获取验证码")
    @GetMapping("send/{phone}")
    public Result send(
            @ApiParam(name = "phone", value = "手机号", required = true)
            @PathVariable String phone) {
        // 从redis中获取验证码 如果能获取到数据就直接返回
        String code = stringRedisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)) {
            return Result.ok().message("短信发送成功");
        }
        // 如果从redis中取不到 就从腾讯云发送
        // 生成随机数 传递腾讯云进行发送
        code = RandomUtil.getSixBitRandom();
        // 调用service发送短信的方法
        boolean flag = smsService.send(phone, code);
        if (!flag) {
            return Result.fail().message("短信发送失败");

        }
        // 发送成功 将验证码放到redis中 设置有效时间
        stringRedisTemplate.opsForValue().set(phone,code,2, TimeUnit.MINUTES);
        return Result.ok().message("短信发送成功");
    }
}
